package com.book.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.pojo.Address;
import com.book.pojo.CartVo;
import com.book.pojo.Order;
import com.book.pojo.User;
import com.book.service.AddressService;
import com.book.service.CartService;
import com.book.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

//订单控制器
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private CartService cartService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private OrderService orderService;

    //确认订单 (确认时要加载一下当前用户的收获地址)
    @RequestMapping("/confirm")
    public String confirm(String ids, Model model, HttpSession session){
        //查询记录
        List<CartVo> cartVos = cartService.findCartByIds(ids);

        //获取当前用户的收货地址
        QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
        User user = (User)session.getAttribute("user");
        addressQueryWrapper.eq("user_id", user.getId());
        List<Address> addressList = addressService.list(addressQueryWrapper);

        //将购买的商品信息添加到session中 方便提交订单的时候调用
        session.setAttribute("cartVos", cartVos);

        model.addAttribute("list", cartVos);
        model.addAttribute("addressList", addressList);
        return "confirm_order";
    }

    //提交订单
    @RequestMapping("/commitOrder")
    public String commitOrder(Integer addrId,Integer status, HttpSession session){
        //从session中拿到 订单里面的商品信息
        List<CartVo> cartVos = (List<CartVo>)session.getAttribute("cartVos");

        System.err.println(cartVos);

        //处理订单 并从购物车中删除 购买的商品
        String flag = orderService.buy(cartVos, addrId,status, session);

        if("success".equals(flag)){
            return "redirect:/order/list";   //跳转到订单列表页
        }else {
            return "redirect:/";   //出错 去首页
        }
    }

    //显示用户订单列表
    @RequestMapping("/list")
    public String list(HttpSession session, Model model){
        User user = (User)session.getAttribute("user");

        List<Order> orders = orderService.findUserOrder(user.getId());

        model.addAttribute("orders", orders);

        return "order_list";
    }

}
